<script lang="ts" setup>
import { ref, h, reactive, onMounted,onBeforeMount } from "vue";
import { ReVxeGrid } from "@/components/ReVxeTable";
import { VxeGridPropTypes, VxeUI } from "vxe-table";
import { VxeFormProps, VxeButton,VxeSwitch,VxeImage } from "vxe-pc-ui";
import { templateList,taxSourcesList,editStatus,listMerchantName,templateRemove } from '@/api/project/project'
const reVxeGridRef = ref();
import templateModal from './components/templateModal.vue'
import auditModal from './components/auditModal.vue'
import { useRouter, useRoute } from "vue-router";
const router = useRouter();
const route = useRoute();
onBeforeMount(() => {
  
  if (!Number.isNaN(Number(route.query?.auditState))) { 
    formOptions.data.auditState = Number(route.query?.auditState);
  }
});
onMounted(() => {
  getalllist();
  getmerchantList();
});
const allList = ref<any[]>()
const getalllist = ()=>{
  taxSourcesList({merchantsInfoId: formOptions.data.merchantsInfoId}).then(res=>{
    allList.value = res?.data?.rows;
  })
}
const merchantList = ref<any[]>()
const getmerchantList = ()=>{
  listMerchantName().then(res=>{
    merchantList.value = res?.data?.rows;
  })
}
const merchantChange = ()=>{
  formOptions.data.taxSourcesId = '';
  getalllist();
}
// 驳回
const auditModalRef = ref();
const stateOptions = ref<any[]>([{
  label: '待审核',
  value: 0
},{
  label: '已通过',
  value: 1
},{
  label: '已停用',
  value: 2
}])

const columns: VxeGridPropTypes.Columns<any> = [
  // { type: "seq", title: "序号", width: 60, align: "center" },
  {
    title: "项目模板ID",
    field: "templateNumber",
    align: "center",
    minWidth: 100,
    showOverflow: true
  },
  {
    title: "税源地",
    field: "taxSourcesIdDisplay",
    align: "center",
    minWidth: 100
  },
  {
    title: "商户名称",
    field: "merchantsName",
    align: "center",
    minWidth: 100
  },
  {
    title: "项目名称",
    field: "projectName",
    align: "center",
    minWidth: 100
  },
  {
    title: "项目内容",
    field: "projectSettlementRules",
    align: "center",
    minWidth: 100
  },
  {
    title: "审核状态",
    field: "auditStateDisplay",
    align: "center",
    minWidth: 100
  },
  {
    title: "模板状态",
    field: "merchantsDealState",
    align: "center",
    minWidth: 100,
    slots: {
      default: ({ row }) => {
        if(row.auditState == 0 || row.auditState == 2){
          return row.merchantsDealStateDisplay
        }else if(row.auditState == 1){
          return h(VxeSwitch,{
            openValue: 1,
            closeValue: 2,
            modelValue: row.merchantsDealState,
            async onChange(res){
              const type = await VxeUI.modal.confirm('确认修改状态？');
              let value = res?.value;
              if(type == 'confirm'){
                changeState({id:row.id,merchantsDealState: value});
              }
            }
          })
        }
        
      }
    }
  },
  {
    title: "创建时间",
    field: "createTime",
    align: "center",
    minWidth: 100
  },
  {
    title: "操作",
    field: "operate",
    align: "center",
    fixed: `right`,
    minWidth: 100,
    slots: {
      default: ({ row }) => {
        let list = [h(VxeButton, {
              status: "primary",
              mode: "text",
              size: "mini",
              content: "查看",
              onClick() {
                templateModalRef.value.showViewModal(row);
              }
            }),h(VxeButton, {
              status: "primary",
              mode: "text",
              size: "mini",
              content: "编辑",
              onClick() {
                templateModalRef.value.showEditModal(row);
              }
            }),h(VxeButton, {
              status: "primary",
              mode: "text",
              size: "mini",
              content: "删除",
              async onClick() {
                const type = await VxeUI.modal.confirm('确认删除该模板?');
                if (type == 'confirm') {
                  deleteone(row);
                }
              }
            }),h(VxeButton, {
              status: "primary",
              mode: "text",
              size: "mini",
              content: "审核通过",
              async onClick() {
                const type = await VxeUI.modal.confirm('请确认是否审核通过?');
                if (type == 'confirm') {
                  changeState({auditState:1,id:row.id})
                 }
              }
            }),h(VxeButton, {
              status: "primary",
              mode: "text",
              size: "mini",
              content: "驳回",
              onClick() {
                auditModalRef.value.showAddModal(row);
              }
            })]
            if(row.auditState == 0){
              return [list[0],list[3],list[4]]
            }else if(row.auditState == 1){
              return [list[0],list[1],list[2]]
            }else if(row.auditState == 2){
              return [list[0],list[2]]
            }
        
      }
    }
  }
];
const deleteone = (params:any)=>{
  templateRemove(params.id).then(res => {
    handleSearch();
  })
}
const changeState = (params:any) => {
  editStatus(params).then(res => {
    handleSearch();
  })
}
// 筛选相关
const formRef = ref();
interface FormDataVO {
  templateNumber: string;//模板id
  projectName: string;//项目名称
  merchantsInfoId: number | string;//商户
  taxSourcesId: number | string; // 税源地
  auditState: number | string;//审核状态
  merchantsDealState: number | string;//模板状态
}
const formOptions = reactive<VxeFormProps<FormDataVO>>({
  data: {
    templateNumber: '',
    projectName: '',
    merchantsInfoId: '',
    taxSourcesId: '',
    auditState: '',
    merchantsDealState: ''
  },
  items: [
    {
      field: "templateNumber",
      title: "",
      span: 4,
      itemRender: {},
      slots: { default: "templateNumber" }
    },
    {
      field: "projectName",
      title: "",
      span: 4,
      itemRender: {},
      slots: { default: "projectName" }
    },
    {
      field: "merchantsInfoId",
      title: "",
      span: 4,
      itemRender: {},
      slots: { default: "merchantsInfoId" }
    },
    {
      field: "taxSourcesId",
      title: "",
      span: 4,
      itemRender: {},
      slots: { default: "taxSourcesId" }
    },
    {
      field: "auditState",
      title: "",
      span: 4,
      slots: { default: "auditState" }
    },
    {
      field: "merchantsDealState",
      title: "",
      span: 4,
      slots: { default: "merchantsDealState" }
    },
    { align: "left", span: 4, slots: { default: "active" } }
  ]
});
//模板状态
const DealState = ref<any[]>([{
  value: 1,
  label: '正常'
}, {
  value: 2,
  label: '停用'
}])
// 重置内容
const handleInitialFormParams = () => {
  formOptions.data = <FormDataVO>{
    templateNumber: '',
    projectName: '',
    merchantsInfoId: '',
    taxSourcesId: '',
    auditState: '',
    merchantsDealState: ''
  };
};
const handleSearch = () => {
  reVxeGridRef.value.loadData();
};
const handleReset = async () => {
  await handleInitialFormParams();
  reVxeGridRef.value.loadData("reset");
};

const templateModalRef = ref();
const handleAdd = () => {
  templateModalRef.value.showAddModal();
};
const handleEdit = (record: Recordable) => {
  templateModalRef.value.showEditModal(record);
};

const handleDelete = async (record: Recordable) => {
  const type = await VxeUI.modal.confirm("您确定要删除吗？");
  if (type == "confirm") {
    // deleteData(record.id).then(() => {
    //   handleSearch();
    // });
  }
};

const handleView = (record: Recordable) => {
  templateModalRef.value.showViewModal(record);
};
const functions: Record<string, string> = {
  add: "platform.client.index.add",
  edit: "platform.client.index.edit",
  view: "platform.client.index.view",
  delete: "platform.client.index.delete"
};

// 时间戳转
// function formatDate (time) {//时间戳转日期
//     let date = new Date(time);
//     let y = date.getFullYear();
//     let MM = date.getMonth() + 1;
//     MM = MM < 10 ? ('0' + MM) : MM;
//     let d = date.getDate();
//     d = d < 10 ? ('0' + d) : d;
//     let h = date.getHours();
//     h = h < 10 ? ('0' + h) : h;
//     let m = date.getMinutes();
//     m = m < 10 ? ('0' + m) : m;
//     let s = date.getSeconds();
//     s = s < 10 ? ('0' + s) : s;
//     return y + '-' + MM + '-' + d + ' ' + h + ':' + m + ':' + s;
//     // return y + '-' + MM + '-' + d;
// }
</script>
<template>
  <div>
    <el-card :shadow="`never`">
      <vxe-form ref="formRef" v-bind="formOptions">
        <template #templateNumber="{ data }">
          <el-input
            clearable
            placeholder="请输入模板ID"
            v-model="data.templateNumber"
          ></el-input>
        </template>
        <template #projectName="{ data }">
          <el-input
            clearable
            placeholder="请输入项目名称"
            v-model="data.projectName"
          ></el-input>
        </template>
        <template #merchantsInfoId="{ data }">
          <el-select
            clearable
            placeholder="请选择商户名称"
            v-model="data.merchantsInfoId"
            @change="merchantChange"
          >
            <el-option
              v-for="(item, index) in merchantList"
              :key="index"
              :label="item.merchantsName"
              :value="item.id"
            ></el-option>
          </el-select>
        </template>
        <template #taxSourcesId="{ data }">
          <el-select
            clearable
            placeholder="请选择税源地"
            v-model="data.taxSourcesId"
          >
            <el-option
              v-for="(item, index) in allList"
              :key="index"
              :label="item.taxSourcesName"
              :value="item.taxSourcesId"
            ></el-option>
          </el-select>
        </template>
        <template #auditState="{ data }">
          <el-select
            clearable
            placeholder="请选择审核状态"
            v-model="data.auditState"
          >
            <el-option
              v-for="(item, index) in stateOptions"
              :key="index"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </template>
        <template #merchantsDealState="{ data }">
          <el-select
            clearable
            placeholder="请选择模板状态"
            v-model="data.merchantsDealState"
          >
            <el-option
              v-for="(item, index) in DealState"
              :key="index"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </template>
        <template #active>
          <el-button @click="handleReset" native-type="reset">重置</el-button>
          <el-button @click="handleSearch" native-type="submit" type="primary"
            >提交</el-button
          >
        </template>
      </vxe-form>
      <div class="mt-3">
        <el-button @click="handleAdd" plain type="primary">创建模板</el-button>
      </div>
    </el-card>
    <el-card :shadow="`never`" class="table-card">
      <ReVxeGrid
        ref="reVxeGridRef"
        :request="templateList"
        :functions="functions"
        :searchParams="formOptions.data"
        :columns="columns"
        :action="false"
        @handleAdd="handleAdd"
        @handleView="handleView"
        @handleDelete="handleDelete"
      />
    </el-card>
    <templateModal ref="templateModalRef" @reload="handleSearch"></templateModal>
    <auditModal ref="auditModalRef" @reload="handleSearch"></auditModal>
  </div>
</template>
<style>
.form_header {
  font-size: 15px;
  color: #6379bb;
  border-bottom: 1px solid #ddd;
  padding-bottom: 5px;
}
.left-title {
  font-weight: 700;
  font-family: 微软雅黑;
  font-size: 14px;
  width: 85px;
  text-align: right;
}
.right-text {
  font-size: 14px;
}



.avatar-uploader .el-upload {
  border: 1px dashed #eee;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: #eee;
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 138px;
  height: 138px;
  text-align: center;
}
.avatar {
  width: 138px;
  height: 138px;
}
.e_footer {
  position: absolute;
  left: 0;
  bottom: 0;
  width: 100%;
  background: #fff;
}
</style>
